package com.dreamscope.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * This class is responsible for validating username and password
 * After validation, it delegates the request object to a servlet which
 * will actually verify the existance of the username and password from the database.
 * 
 * @author ajain37
 *
 */
public class LoginServlet extends HttpServlet {
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		String username = request.getParameter("qparam1");
		String password = request.getParameter("qparam2");
		
		System.out.println(username+"/"+password);
		password = decrypt(password);
		System.out.println("Decrypted Password: "+password);
		
		//TODO: Authenticate user from MySQL Database;
		Connection conn =null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		boolean userAuthenticated = false;
		try{
			Class.forName("com.mysql.jdbc.Driver"); 
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dreamscope","root","computer");
			System.out.println(conn);
			if(conn!=null && !conn.isClosed()){
				System.out.println("Successfully Connected to DB");
				String query = "SELECT * FROM users WHERE name = ? and pass = ?";
				pstmt = conn.prepareStatement(query);
				pstmt.setString(1,username);
				pstmt.setString(2,password);
				
				rs = pstmt.executeQuery();
				while((rs!=null)&& (rs.next())){
					if( (rs.getString(1)!=null) && ( rs.getString(2)!=null))
						userAuthenticated = true;
				}
				if(userAuthenticated){
					//TODO: Attach a proper session identifier for this user
					
					PseudoSessionBean sessionBean = new PseudoSessionBean();
					String userSessionId = sessionBean.getSessionID(request);
					sessionBean.setValue(userSessionId,"username",username);
					
					out.print("Welcome Aboard! "+username +":your session id is:"+userSessionId);
				}
				else{
					RequestDispatcher rd = request.getRequestDispatcher("pages/main/login.jsp");
					request.setAttribute("loginFailureMsg","Invalid Username/Password");
					rd.forward(request,response);
//					out.print("Invalid Username/password, Please enter correct username and password or register yourself.");
				}
			}
			
		}catch(SQLException ex){
			ex.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("Driver could not be loaded for making connection !"+e.getLocalizedMessage());
		}finally{
			try {
				if(rs!=null)
					rs.close();
				if(pstmt!=null)
					pstmt.close();
				if(conn!=null)
					conn.close();
			} catch (SQLException e) {
				System.out.println("Could not close connection"+e.getMessage());
			}
		}
	}
	
	private String decrypt(String theText) {
		String output = new String();
		int textSize = theText.length();
		char[] temp= theText.toCharArray();
		for(int i=0;i<textSize;i++){
			temp[i] = (char)(temp[i]- 68);
			output += temp[i];
		}
		return output;
	}

}
